package ks.server.persist;

import java.net.URL;
import java.util.Collection;

import ks.managers.icon.Icon;
import ks.managers.icon.IconManager;

public class PersistentIconManager extends IconManager {

	/** Protect access to this constructor. */
	public PersistentIconManager() {
		super();
		
		initialize();
	}

	private void initialize() {
		try {
			Collection<Icon> icons = Database.getIcons();
			for (Icon ic : icons) {
				knownIcons.put(ic.name, ic);
			}
		} catch (Exception e) {
			System.err.println("Unable to populate from db");
		}
	}
	
	/**
	 * Adds the given Icon by name and URL to be associated with that icon.
	 * <p>
	 * 
	 * @param iconName
	 * @param url
	 */
	public boolean add (String iconName, URL url) {
		
		// try to add to DB
		try {
			if (!Database.addIcon(iconName, url.toString())) {
				System.err.println("Unable to add Icon to persistent database");
				return false;
			}
			
			super.add(iconName, url);
		} catch (Exception e1) {
			System.err.println("Unable to add icon to persistent database: " + iconName);
			return false;
		}

		// done
		return true;
	}
	
}
